import React from 'react';
import { Row, Col, Button, Popover } from 'antd';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { WeaTools,WeaErrorPage,WeaTop, WeaTab, WeaSearchPanel, WeaLeftRightLayout, WeaReportCard,WeaTree } from 'ecCom';
import { WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

import {Link,hashHistory} from 'react-router';

import SearchComponent from '../common/SearchComponent'

import '../../../workflow/util/windowFun';//支持openSPA4Single,doPrintRequest,showallreceived等方法

@inject("centerStore")
@observer
class CenterComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {library_width: 0,todo_width:0};
  }
  
  componentWillMount(){
    const { centerStore } = this.props;
    centerStore.buildCreateReq();
    centerStore.buildCreateOffical();
    centerStore.buildCountOfOdocType();
    centerStore.buildCountOfTopicType();
    centerStore.buildSearchCondition();
    centerStore.buildLibrarys();
    centerStore.buildTodos();
    centerStore.buildTodoTabs();
  }

  componentDidMount() {
    let library_width = ($("#rowLibrarys").width()/2-16)*0.9;
    let todo_width = ($("#rowTodos").width()-32-20-100);
    this.setState({library_width : library_width,todo_width:todo_width});
    window.addEventListener('resize', this.resize.bind(this));
  }

  resize(){
    let library_width = ($("#rowLibrarys").width()/2-16)*0.9;
    let todo_width = ($("#rowTodos").width()-32-20-100);
    this.setState({library_width : library_width,todo_width:todo_width});
  }

  renderCreateReqTree(treeDatas,expandedKeys,key){
    const { centerStore } = this.props;
    return (
    <WeaTree 
      datas={treeDatas} 
      expandedKeys={expandedKeys} 
      hasRadio = {true}
      renderNode={(node)=>{
        if(node.haschild){
          return <span className="wea-odoc-center-left-tree-parentnode" title={node.name}>{node.name}</span>
        }else{
         return <span title={node.name}>{node.name}</span>;
        }
      }}
      onSelect={(ids, nodeids, nodes, event)=>{
         let node = nodes[0];
         if(!node.haschild){
          centerStore.popoverChange( false,key)
          centerStore.addWorkflowUseCount(node.workflowid);
          let paramstr = 'workflowid='+node.workflowid+'&isagent='+node.isagent+'&beagenter='+node.beagenters+'&f_weaver_belongto_userid='+node.belongtoUsers+'&f_weaver_belongto_usertype=0';
          openFullWindowHaveBar('/workflow/request/CreateRequestForward.jsp?'+paramstr);
         }
       }}/>);
  }

  //渲染 公文创建 大类
  renderCreateReq(){
    const { centerStore } = this.props;
    let createReq  = toJS(centerStore.createReq);
    let createOffical =  toJS(centerStore.createOffical);

    let isShowCreateReqDraftDialog = createOffical[0].createOfficalList.length > 0 ? true : false;
    let isShowCreateReqReceiptDialog = createOffical[1].createOfficalList.length > 0 ? true : false;

    const content1 = (
      <div>
        {this.renderCreateReqTree(createOffical[0].createOfficalList,createOffical[0].createOfficalListKeys,"popover1")}
      </div>
    );
    const content2 = (
      <div>
        {this.renderCreateReqTree(createOffical[1].createOfficalList,createOffical[1].createOfficalListKeys,"popover2")}
      </div>
    );

    const btnStyleFW = {
      backgroundColor : "#F66D55",//createReq.createReqDraft.bgcolor,
      color:createReq.createReqDraft.color
    }
    const btnStyleSW = {
      backgroundColor : "#2DB7F5",//createReq.createReqReceipt.bgcolor,
      color:createReq.createReqReceipt.color
    }
    return (<Row className="wea-odoc-center-left-row">
    <Col span="12" >
      {
        isShowCreateReqDraftDialog &&
        <Popover overlayClassName="wea-odoc-center-left-popover" placement="bottomLeft"  content={content1} trigger="click" visible={centerStore.popover1} onVisibleChange={(bool)=>centerStore.popoverChange(bool,"popover1")}>
        <div className="wea-odoc-center-bigbutton-wrapper"> <div  className="wea-odoc-center-bigbutton1"><span>{createReq.createReqDraft.showName}</span></div></div>
      </Popover>
      }
      {
        !isShowCreateReqDraftDialog &&
        <div className="wea-odoc-center-bigbutton-wrapper"> <div  className="wea-odoc-center-bigbutton1"><span>{createReq.createReqDraft.showName}</span></div></div>
      }
    </Col>
    <Col span="12">
    {
      isShowCreateReqReceiptDialog && 
      <Popover overlayClassName="wea-odoc-center-left-popover" placement="bottomLeft"  content={content2} trigger="click" visible={centerStore.popover2} onVisibleChange={(bool)=>centerStore.popoverChange(bool,"popover2")}>
        <div className="wea-odoc-center-bigbutton-wrapper"><div  className="wea-odoc-center-bigbutton2" ><span>{createReq.createReqReceipt.showName}</span></div></div>
      </Popover>
    }
    {
      !isShowCreateReqReceiptDialog &&
      <div className="wea-odoc-center-bigbutton-wrapper"><div  className="wea-odoc-center-bigbutton2" ><span>{createReq.createReqReceipt.showName}</span></div></div>
    }
    
    </Col>
  </Row>);
  }

  renderCountByOdocType(){
    const { centerStore } = this.props;
    let countOfOdocType = toJS(centerStore.countOfOdocType);
    let rows = [];
    if(countOfOdocType.dataList){
      countOfOdocType.dataList.map((data,index) => {
        rows.push(<Col span="12"><div onClick={()=>this.jumpToLibraryForOdocType("1|"+data.odoctype+"|"+data.showname)} title={data.showname} className="left_c1"><span className="span1">{data.showname}</span>  <span className="span2">{data.count}</span></div></Col>);
      })
    }

    return (<Row className="wea-odoc-center-left-row">
    <Col>
      <div className="wea-info-group-new">
        <Row className="wea-info-group-new-title">
          <Col>
            <div className="wea-info-group-new-title-info">&nbsp;&nbsp;{countOfOdocType.showname}（{countOfOdocType.totalCount}）</div>
          </Col>
        </Row>
        <Row className="wea-info-group-new-content" >
          <Col>
          {rows}
          </Col>
        </Row>
      </div>
    </Col>
  </Row>);
  }

  renderCountByTopicType(){
    const { centerStore } = this.props;
    let countOfTopicType = toJS(centerStore.countOfTopicType);

    let rows = [];
    if(countOfTopicType.dataList){
      countOfTopicType.dataList.map((data,index) => {
        let leftspan_className = "";
        if(index<3){
          leftspan_className="leftspan_1";
        }else{
          leftspan_className="leftspan_2";
        }
        rows.push(<Col span="24"><div onClick={()=>this.jumpToLibraryForTopicType("1|"+data.topictype+"|"+data.showname)} title={data.showname} className="left_c2"><div className="leftdiv"><span className={leftspan_className}>{index+1}</span></div><span className="centerspan">{data.showname}</span>  <span className="rightspan">{data.count}</span></div></Col>);
      })
    }

    return ( <Row className="wea-odoc-center-left-row">
    <Col>
      <div className="wea-info-group-new">
        <Row className="wea-info-group-new-title">
          <Col>
            <div className="wea-info-group-new-title-info"> {countOfTopicType.showname}（{countOfTopicType.totalCount}）</div>
          </Col>
        </Row>
        <Row className="wea-info-group-new-content" >
          <Col>
          {rows}
          </Col>
        </Row>
      </div>
    </Col>
  </Row>);
  }

  renderLeft() {
    return (<div className="wea-odoc-center-left" >
     {this.renderCreateReq()}
     {this.renderCountByOdocType()}
     {this.renderCountByTopicType()}
    </div>);
  }

  renderSearchAdButtons() {
    const { centerStore } = this.props;
    return [
      (<Button type="primary" onClick={() => this.jumpToLibraryForAll()}>{getLabel('197',"搜索")}</Button>),
      (<Button type="ghost" onClick={() => centerStore.resetForm()}>{getLabel('2022',"重置")}</Button>),
      (<Button type="ghost" onClick={() => {
        centerStore.resetForm();
        centerStore.searchStore.changeShowSearchAd(false);
        }}>{getLabel('31129',"取消")}</Button>)
    ]
  }

  renderLibrarys(){
    const { centerStore } = this.props;
    let librarys = toJS(centerStore.librarys);
    let rows = [];
    let library_width = this.state.library_width;

    if(librarys.length>0){
      librarys.map((data,index) => {
        rows.push(<Col span={12}>
        <div className="right_c1">
          <div className="right_c1_r">
            <div className="right_c1_r-top">
            <p style={{width:library_width}} dangerouslySetInnerHTML={{__html: data.showlink}} />
              </div>
            <div className="right_c1_r-bottom">
              {data.createdatetime}&nbsp;&nbsp;&nbsp;&nbsp;
            </div >
          </div>
        </div>
        
        </Col>);
      })
    }
//<div className="right_c1"><span><a dangerouslySetInnerHTML={{__html:data.showlink}} /></span></div>
    return (rows);
  }


  renderTodos(){
    const { centerStore } = this.props;
    let todos = toJS(centerStore.todos);
    let rows = [];
    let todo_width = this.state.todo_width;

    if(todos.length>0){
      todos.map((data,index) => {
        rows.push(<Row>
          <Col>
          <div className="right_c2">
            <div className="right_c2_l">
              <p  class="wea-odoctype-labelp" title={data.odoctypename}>{data.odoctypename}</p>
            </div>
            <div className="right_c2_r">
              <div className="right_c2_r-top">
              <p style={{width:todo_width}} dangerouslySetInnerHTML={{__html: data.showlink}} />
                </div>
              <div className="right_c2_r-bottom">
              <a dangerouslySetInnerHTML={{__html:data.creater}} />  &nbsp;&nbsp;
                {data.createdatetime}&nbsp;&nbsp;&nbsp;&nbsp;
      
              </div >
            </div>
          </div>
          </Col>
          </Row>);
      })
    }
    return (rows);
  }

  renderRight() {
    
    const { centerStore } = this.props;
    return (<div className="wea-odoc-center-right" style={{ padding: 8 }}>
      <Row className="wea-odoc-center-right-row">
        <Col>
          <WeaSearchPanel
            style={{ height: 400,width: 800 }}
            searched={centerStore.searchStore.searched}
            inputValue={centerStore.getSearchsBaseValue()}
            onSearch={v => this.jumpToLibraryForOdocSubject(v)}
            onSearchChange={v => centerStore.setSearchsBaseValue(v)}
            buttonsAd={this.renderSearchAdButtons()}
            searchsAd={<SearchComponent searchStore={centerStore.searchStore} />}
            visible={centerStore.searchStore.showSearchAd}
            onVisibleChange={v => centerStore.searchStore.changeShowSearchAd(v)}
          />
        </Col>
      </Row>
      <Row id="rowLibrarys" className="wea-odoc-center-right-row"><Col>
        <WeaReportCard
          title={<span><span className="icon-coms-yellow-big"><i className='icon-coms-official' /></span>{getLabel('383001',"公文库")}</span>}
          onMoreClick={ v => this.jumpToLibrary()}
        >
       <Row> {this.renderLibrarys()}</Row>
         
        </WeaReportCard></Col>
      </Row>
      <Row id="rowTodos" className="wea-odoc-center-right-row"><Col>
        <WeaReportCard
          title={<span><span className="icon-coms-yellow-big"><i className='icon-coms-Planning-tasks' /></span>{getLabel(384728,"待办公文")}</span>}
          onMoreClick={v => this.jumpToTodo()}
        >
          <WeaTab
            datas={centerStore.tabs}
            //counts={centerStore.tabsCount}
            keyParam="viewcondition"  //主键
            countParam="groupid" //数量
            selectedKey={centerStore.selectedTodoTab}
            onChange={selectedKey => centerStore.changeTodoTab(selectedKey)}
          />
          {this.renderTodos()}
         
        </WeaReportCard></Col></Row>
    </div>);
  }

  render() {
    //  alert(Dimensions.get('window').width);
    return (
      <div className="wea-odoc-center-parent">
      <WeaTop
        title={getLabel('384730',"公文中心")}
        // loading={loading}
        icon={<i className='icon-coms-official' />}
        iconBgcolor={"#f14a2d"}
        // showDropIcon={true}

      >
        <div className="wea-odoc-center">
          <WeaLeftRightLayout
            showBtn={false}
            leftWidth={260}
            leftCom={this.renderLeft()}
          >
            {this.renderRight()}
          </WeaLeftRightLayout>
        </div>
      </WeaTop></div>);
  }

  jumpToLibraryForAll(){
    const { centerStore } = this.props;
    let datas = centerStore.searchStore.form.getFormDatas();
    let odoctype = datas.odoctype.value[0];
    if(odoctype=="1"){
      let id = "";
      let name = "";
      if(datas.odoctype.value[1]){
        id = datas.odoctype.value[1][0];
        name=datas.odoctype.value[1][1];
      }
      odoctype = odoctype +"|"+id+"|"+name;
    }

    let topictype = datas.topictype.value[0];
    if(topictype=="1"){
      let id = "";
      let name = "";
      if(datas.topictype.value[1]){
        id = datas.topictype.value[1][0];
        name=datas.topictype.value[1][1];
      }
      topictype = topictype +"|"+id+"|"+name;
    }
    
    let writtendateselect = datas.writtendateselect.value[0];
    if(writtendateselect=="6" && datas.writtendateselect.value[1] && datas.writtendateselect.value[1][0]!=="" &&  datas.writtendateselect.value[1][1]!==""){
      writtendateselect = writtendateselect +"|"+datas.writtendateselect.value[1][0]+"|"+datas.writtendateselect.value[1][1];
    }

    this.jumpToLibrary(
      datas.odocSubject.value,
      odoctype,
      topictype,
      datas.dispatchnum.value,
      writtendateselect,
      datas.readstatus.value);
  }

  jumpToLibraryForOdocSubject(odocSubject){
    this.jumpToLibrary(odocSubject);
  }

  jumpToLibraryForOdocType(odoctype){
    this.jumpToLibrary("",odoctype,"","","","");
  }

  jumpToLibraryForTopicType(topictype){
    this.jumpToLibrary("","",topictype,"","","");
  }

  jumpToLibrary(odocSubject,odoctype,topictype,dispatchnum,writtendateselect,readstatus){
	const {centerStore} = this.props;
	const formData = centerStore.searchStore.form.getFormParams();
    let params ={
	  ...formData,
      odocSubject:odocSubject,
      odoctype:odoctype,
      topictype:topictype,
      dispatchnum:dispatchnum,
      writtendateselect:writtendateselect,
      readstatus:readstatus
    }
	

    var path = {
      pathname:'/main/offical/odocLibrary',
      query:params
    }
    
    hashHistory.push(path);
  }

  jumpToTodo(){
    hashHistory.push("/main/offical/todo");
  }
}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage msg={ props.error ? props.error : '对不起，该页面异常，请联系管理员！'} />,
  { error: '' }
)(CenterComponent);